const api = require('../../../../ws_micro_shop/utils/api.js');
const utils = require('../../../../ws_micro_shop/utils/utils.js');
const tools = require('../../../../ws_micro_shop/utils/getuserinfo.js');
const app = getApp();
const { module: moduleName } = app.siteInfo;
const util = app.util;

let p = 1;

Page({
  data: {
    tab_detail: 'active',
    tab_comment: '',
    comment_list: [],
    idx: 1,
    level: 0,
    img_hide: true,
    hide: 'hide',
    url: '',
    comment_count: {
      score_all: 0,
      score_6: 0,
      score_3: 0,
      score_2: 0,
      score_1: 0,
    },
    showComment: false,
    autoplay: true,
    theme: app.themeData,
    abnorData: {
      imgSrc: '/common/static/images/abnor-09.png',
      text: '暂无相关评价',
    },
    show_service: false,
    unit: '',
    imgUrl: app.imgUrl,
    floatItems:[{
      type: 0, // 推荐
      show: false,
      iconClass: 'icon icon-xin',
      event: 'recommend',
    }]
  },
  onLoad(ops) {
    this.setData({
      orgPrice: app.ws_micro_shop_globalData.orgPrice,
      isSaas: app.ws_micro_shop_globalData.isSaas
    })
    let options = ops || {};
    app.v8_card_action_log = [];
    let parent_id = 0;
    let shop_id = 0;
    let share_scene = '';
    let user_id = options.user_id;
    let scene = decodeURIComponent(options.scene);
    if (options && options.shopid) {
      app.ws_micro_shop_globalData.shopid = options.shopid;
      shop_id = options.shopid;
    }
    app.tabbarindex = options.tabbarindex ? options.tabbarindex - 0 : app.tabbarindex;
    app.pageOnLoad(this);
    let that = this;
    let userinfo = wx.getStorageSync('user_info');
    let store = wx.getStorageSync('store');
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    app.loadShopSetting()
      .then(res => {
        that.setData(res);
      })
    if (user_id) {
      parent_id = user_id;
      share_scene = 4;
    } else if (scene) {
      let { uid, gid, sid } = utils.scene_decode(scene);
      if (uid && gid) {
        parent_id = uid;
        options.id = gid;
        shop_id = sid;
        app.ws_micro_shop_globalData.shopid = sid;
      } else {
        parent_id = scene;
      }
      share_scene = 6;
    }
    if (userinfo && store) {
      Number(userinfo.info) === 0 && tools.onGetInfo(this, userinfo.auth_mode);
      store.comment_switch === 1 && this.getComments(options.id, 0, 1);
      this.setData({ store });
      app.loginBindParent({
        parent_id,
        shop_id,
        share_scene,
      });
      util.prepareBindInfo(options, moduleName, that);
      this.bindCard(options);
    } else {
      app.ws_micro_shoplogin().then(res => {
        userinfo = wx.getStorageSync('user_info');
        Number(userinfo.info) === 0 && tools.onGetInfo(that, userinfo.auth_mode);
        util.prepareBindInfo(options, moduleName, that);
        this.bindCard(options);
        app.getStoreData().then(res => {
          store = wx.getStorageSync('store');
          store.comment_switch === 1 && that.getComments(options.id, 0, 1);
          that.setData({ store });
          app.loginBindParent({
            parent_id,
            shop_id,
            share_scene,
          });
        });
      });
    }
    this.setData({
      opts: options,
      id: options.id,
      userinfo,
      store,
    });
    p = 1;
    this.getGoodsInfo(options);
    this.checkUserCardManage();
  },
  onReachBottom() {
    if (this.data.showComment) {
      p++;
      this.getComments(this.data.id, this.data.level, p);
    }
  },
  onShareAppMessage() {
    let that = this;
    let { userinfo, goods } = that.data;
    let path = '/ws_micro_shop_book/pages/book/details/details?id=' + goods.id + '&user_id=' + userinfo.id + '&tabbarindex=' + app.tabbarindex + '&shopid=' + app.ws_micro_shop_globalData.shopid;
    path = util.spliceSharePath(path, '4', moduleName);
    let shareShowPrice = wx.getStorageSync('store') && wx.getStorageSync('store').share_show_price;
    return {
      title: `${Number(shareShowPrice) === 1 ? that.data.goods.price + '元' : ''}${that.data.goods.name}`,                  
      path,
      imageUrl: goods.cover_pic,
    };
  },
  onShareTimeline() {
    let that = this;
    let { userinfo, goods } = that.data;
    let shareShowPrice =
      wx.getStorageSync("store") && wx.getStorageSync("store").share_show_price;
    return {
      title: `${
        Number(shareShowPrice) === 1 ? that.data.goods.price + "元" : ""
      }${that.data.goods.name}`,
      imageUrl: goods.cover_pic,
      query:
        "id=" +
        goods.id +
        "&user_id=" +
        userinfo.id +
        "&tabbarindex=" +
        app.tabbarindex +
        "&shopid=" +
        app.ws_micro_shop_globalData.shopid,
    };
  },
  onHide() {
    util.sendBindInfo(this.data);
  },
  onUnload() {
    util.sendBindInfo(this.data);
  },
  bindCard(options) {
    app.bindCard(options.openid, options.share_scene);
    app.v8_card_action_log.push({ name: 'transmitGoods', data:{goodsID: options.id, type: 'book'}, timestamp: new Date().getTime(), to_openid: options.openid });
    app.util.statRequest({
      aa: JSON.stringify(app.v8_card_action_log),
      is_module: 0
    });
  },
  getGoodsInfo(e) {
    let gid = e.id;
    let that = this;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.book.details,
      method: 'GET',
      data: { gid },
      success: function(res) {
        if (res.code === 0) {
          let resp = res.data;
          let info = resp.info;
          let { detail, virtual_sales, sales } = info;
          sales = (parseInt(virtual_sales, 0) + parseInt(sales, 0));
          that.setData({
            goods: info,
            shop: resp.shopList,
            sales,
            detail,
            show_goods_comment: resp.show_goods_comment,
            show_download_icon: resp.show_download_icon,
          });
        } else if (res.code === -3) {
          app.ws_micro_shoplogin().then(res => {
            let userinfo = wx.getStorageSync('user_info');
            Number(userinfo.info) === 0 && tools.onGetInfo(that, userinfo.auth_mode);
            util.prepareBindInfo(that.data.opts, moduleName, that);
            app.getStoreData().then(res => {
              let store = wx.getStorageSync('store');
              Number(store.comment_switch) === 1 && that.getComments(that.data.opts.id, 0, 1);
              that.setData({ store });
              app.loginBindParent({
                parent_id: that.data.parent_id,
                shop_id: that.data.shop_id,
                share_scene: that.data.share_scene,
              });
            });
            that.getGoodsInfo(that.data.opts);
          });
        } else {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                app.util.navigateTo('/ws_micro_shop_book/pages/book/index/index', {}, true);
              }
            },
          });
        }
      },
      complete: function() {
        setTimeout(function() {
          wx.hideLoading();
        }, 1000);
      },
    });
  },
  tabSwitch(e) {
    let tab = e.currentTarget.dataset.tab;
    if (tab === 'detail') {
      this.setData({
        tab_detail: 'active',
        tab_comment: '',
        showComment: false,
      });
    } else {
      this.setData({
        tab_detail: '',
        tab_comment: 'active',
        showComment: true,
      });
    }
  },
  commentPicView(e) {
    let { index, pic_index } = e.currentTarget.dataset;
    let pic_list = this.data.comment_list[index].pic_list;
    wx.previewImage({
      current: pic_list[pic_index],
      urls: pic_list,
    });
  },
  bespeakNow() {
    wx.navigateTo({
      url: '/ws_micro_shop_book/pages/book/submit/submit?id=' + this.data.goods.id,
    });
  },
  goToShopList() {
    wx.navigateTo({
      url: '/ws_micro_shop_book/pages/book/shop/shop?ids=' + this.data.goods.shop_id,
    });
  },
  switchComment(e) {
    let { idx, level } = e.currentTarget.dataset;
    p = 1;
    this.setData({
      comment_list: [],
      idx,
      level,
    });
    wx.showToast({
      title: '加载中...',
      icon: 'loading',
    });
    this.getComments(this.data.id, level, p);
  },
  getComments(id, score, page) {
    let that = this;
    wx.showToast({
      title: '加载中...',
      icon: 'loading',
    });
    app.ws_micro_shoprequest({
      url: api.book.goods_comment,
      method: 'GET',
      data: {
        goods_id: id,
        score,
        page,
      },
      success: function(res) {
        wx.hideToast();
        let { comment_count, list } = res.data;
        if (list.length > 0) {
          that.setData({
            comment_count,
            comment_list: that.data.comment_list.concat(list),
          });
        } else {
          if (that.data.showComment) {
            wx.showToast({
              title: '没有更多数据了',
              duration: 1500,
              icon: 'none',
            });
          }
        }
      },
    });
  },
  showShareModal() {
    this.setData({
      share_modal_active: 'active',
      no_scroll: true,
    });
  },
  shareModalClose() {
    this.setData({
      share_modal_active: '',
      no_scroll: false,
    });
  },
  disabledClick() {
    // it`s necessary
  },
  getGoodsQrcode() {
    let that = this;
    that.setData({
      goods_qrcode_active: 'active',
      share_modal_active: '',
    });
    if (that.data.goods_qrcode) {
      return true;
    }
    app.ws_micro_shoprequest({
      url: api.book.goods_qrcode,
      data: {
        goods_id: that.data.id,
      },
      success: function(res) {
        if (res.code === 0) {
          that.setData({
            goods_qrcode: res.data.pic_url,
          });
        }
        if (res.code === 1) {
          that.goodsQrcodeClose();
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
          });
        }
      },
    });
  },
  goodsQrcodeClose() {
    this.setData({
      goods_qrcode_active: '',
      no_scroll: false,
    });
  },
  saveGoodsQrcode() {
    let that = this;
    if (!wx.saveImageToPhotosAlbum) {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        showCancel: false,
      });
      return;
    }
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting['scope.writePhotosAlbum'] === 'undefined') {
          that.downLoadGoodsImg();
        } else if (res.authSetting['scope.writePhotosAlbum'] === false) {
          that.setData({
            open_setting: true,
          });
        } else {
          that.downLoadGoodsImg();
        }
      },
    });
  },
  downLoadGoodsImg() {
    let _this = this;
    wx.showLoading({
      title: '正在下载图片',
      mask: true,
    });
    wx.downloadFile({
      url: _this.data.goods_qrcode,
      success: function(e) {
        wx.showLoading({
          title: '正在保存图片',
          mask: true,
        });
        wx.saveImageToPhotosAlbum({
          filePath: e.tempFilePath,
          success: function() {
            wx.showModal({
              title: '提示',
              content: '商品海报保存成功',
              showCancel: false,
            });
          },
          fail: function(e) {
            wx.showModal({
              title: '提示',
              content: '图片保存失败',
              showCancel: false,
            });
          },
          complete: function(e) {
            wx.hideLoading();
          },
        });
      },
      fail: function(e) {
        wx.showModal({
          title: '图片下载失败',
          content: e.errMsg + ';' + _this.data.goods_qrcode,
          showCancel: false,
        });
      },
      complete: function(e) {
        wx.hideLoading();
      },
    });
  },
  goodsQrcodeClick(e) {
    let src = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [src],
    });
  },
  play(e) {
    let url = e.currentTarget.dataset.url;
    this.setData({
      url: url,
      hide: '',
      autoplay: false,
    });
    let videoContext = wx.createVideoContext('video');
    videoContext.play();
  },
  close(e) {
    if (e.currentTarget.id === 'video') {
      return true;
    }
    this.setData({
      hide: 'hide',
      autoplay: true,
    });
    let videoContext = wx.createVideoContext('video');
    videoContext.pause();
  },
  hide(e) {
    this.setData({
      img_hide: Number(e.detail.current) === 0,
    });
  },
  openService() {
    this.setData({
      show_service: true,
    });
  },
  closeService() {
    this.setData({
      show_service: false,
    });
  },
  onNavigate(e) {
    let param = e.currentTarget.dataset;
    app.util.navigateTo(param.url, {}, true);
  },
  downloadPicture() {
    utils.downLoad(this);
  },
  onGoodsImageClick(e) {
    let urls = this.data.goods;
    let index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: urls.pic_list[index],
      urls: urls.pic_list,
    });
  },
  wxmlTagATap(e) {
    let src = e.detail.src || false;
    let reUrl = /^\//;
    if (!src) {
      return;
    } else {
      reUrl.test(src) ? app.util.navigateTo('/ws_micro_shop' + src) : app.util.navigateTo('/ws_micro_shop/pages/web/web?url=' + src);
    }
  },
  collectFormId(e) {
    app.collectFormId(e);
  },

  // 判断当前模块是否开启了推荐
  checkRecommandBtn(){
    let { floatItems } = this.data;
    app.util.request({
      url:'card/record/getModuleRecommandButton',
      success: res => {
        let {errcode, data} = res.data;
        if(errcode == 0){
          floatItems.forEach(item =>{
            if(item.event == 'recommend'){
              item.show = data == 1? true: false;
            }
          })
          this.setData({
            floatItems
          })
        }
      }
    })
  },

  // 判断当前用户是否有名片及商品是否被加入到名片推荐商品中
  checkUserCardManage(){
    let { id } = this.options;
    let { floatItems } = this.data;
    app.util.request({
      url:'card/record/getUserCardManage',
      data:{
        id,
        type:'4',
        openid: wx.getStorageSync('openid') || wx.getStorageSync('OPENID')
      },
      success: res => {
        let {errcode, data:{is_cardmanage,is_havegoods}} = res.data;
        console.log("=====checkUserCardManage====",res.data);
        this.checkRecommandBtn();
        if(errcode == 0){
          floatItems.forEach(item =>{
            if(item.event == 'recommend'){
              item.show = is_cardmanage == 1? true: false;
              item.iconClass = is_havegoods == 1? 'icon icon-xinxin' :'icon icon-xin';
            }
          })
          this.setData({
            floatItems,
            is_havegoods
          })
        }
      }
    })
  },

  customerTo() {
    let { card_openid, card_toopenid, card_id } = this.data;
    let url = '/common/component/universal-card/pages/message?openid=' + card_openid + '&to_openid=' + card_toopenid + '&cardid=' + card_id + '&scene=inner&m_id=0';
    app.util.navigateTo(url);
  },

  // 添加推荐商品
  recommend(){
    let { id } = this.options;
    let { floatItems, is_havegoods } = this.data;
    console.log("===is_havegoods====",is_havegoods)
    app.util.request({
      url:'card/record/addCardManageGoods',
      data:{
        id,
        type:'4',
        openid: wx.getStorageSync('openid') || wx.getStorageSync('OPENID'),
        options: is_havegoods == 0? '1': '2'
      },
      success: res => {
        console.log("===addCardManageGoods====",res.data.data)
        if(res.data.errcode == 0){
          is_havegoods = !is_havegoods;
          floatItems.forEach(item =>{
            if(item.event == 'recommend'){
              item.iconClass = is_havegoods == 1? 'icon icon-xinxin' :'icon icon-xin';
            }
          })
          let title = is_havegoods == 1?'推荐成功':'取消推荐成功';
          wx.showToast({
            title,
            icon:'none'
          })
        } else {
          wx.showToast({
            title:res.data.errmsg,
            icon:'none'
          })
        }
        this.setData({
          floatItems,
          is_havegoods
        })
      }
    })
  },
});
